package czk.concrent.syn;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/9 22:31
 */

/**
 * syn保证了代码的原子性
 * 即是翻译成的字节码指令的完整行
 * 给临界区加锁是线程的行为
 */
public class Test1 {
    static int j=0;
    private static Object object=new Object();

    public static void main(String[] args) throws InterruptedException {
        Room room=new Room();
        Thread t1=new Thread(()->{
            for (int i=0;i<10;i++){
                synchronized (object) {
                    //System.out.println(++j);;
                    room.increase();
                }
            }

        });
        Thread t2=new Thread(()->{
            for (int i=0;i<10;i++){
                synchronized (object) {
//                    System.out.println(--j);;
                    room.decrease();
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(room.getCount());
    }
}
// 改造
class Room{
    private static int count=0;
    // 封装成方法
    public void increase(){
        synchronized (this){
            count++;
        }
    }
    public void decrease(){
        synchronized (this){
            count--;
        }
    }
    // 为了避免拿到不正确结果
    public Integer getCount(){
        synchronized (this){
            return count;
        }
    }
}
